import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: "/api",
  timeout: 15000 // request timeout
})

// response interceptor
service.interceptors.response.use(
  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.status != 200) {
      Message({
        message: response.data.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(response.msg || 'Error'))
    }

    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 2000) {

      if (res.code == 4002 || res.code ==2001) {
        return res
      } else {
        Message({
          message: response.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }

      return Promise.reject(new Error(response.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug

    if (error.code == "ECONNABORTED" || error.message == "Network Error") {
      Message({
        message: '网络超时，请稍后重试',
        type: 'error',
        duration: 5 * 1000
      })
      return
    }

    Message({
      message: error.msg || 'error',
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
  }
)

export default service
